<template>
  <div class="root" v-loading="loading">
    <el-form :model="createTagFrom" :rules="rules" ref="createTagFrom" label-width="100px" class="demo-ruleForm">
      <el-form-item label="模版名称" prop="modelName">
        <el-input size="mini" placeholder="请输入模版名称" v-model="createTagFrom.modelName" ref="inputRef">
        </el-input>
      </el-form-item>
      <el-form-item label="生成素材名" prop="radio">
        <el-radio-group v-model="createTagFrom.generateStatus" >
          <el-radio :label="1">生成</el-radio>
          <el-radio :label="0">不生成</el-radio>
        </el-radio-group>
      </el-form-item>

      <div style="height: 50px; width: 400px; display: flex" v-show="createTagFrom.generateStatus===1">
        <el-form-item label="组外分隔" style="margin:auto" prop="groupDiv">
          <el-select size="mini" v-model="createTagFrom.groupDiv">
            <el-option v-for="item in divList" :key="item.value" :value="item.value"
                       :label="item.label"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="同组分割" style="margin:auto" prop="tagDiv">
          <el-select size="mini" v-model="createTagFrom.tagDiv">
            <el-option v-for="item in divList" :key="item.value" :value="item.value"
                       :label="item.label"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <el-form-item v-show="createTagFrom.generateStatus===1">
        <div style="display: flex;width: 80px;height: 30px" slot="label">
          <p style="margin: auto;font-size: 15px">
            命名规则
          </p>
          <!--generateName-->
          <el-tooltip style="margin: auto" content="上传素材时会根据选择的规则自动生成素材名称">
            <!--上传素材时会根据选择的规则自动生成素材名称-->
            <i class="el-icon-question" style="color: #9a9a9f"/>
          </el-tooltip>
        </div>
        <el-tag v-for="(it,i) in nameRules" :key="i" :closable="it.name!=='短ID'" style="margin-left: 5px;margin-top: 5px" :type="(it.type==='system')?'info':''"
                @close="handleTagClose(i,it)">
          {{ it.name }}
        </el-tag>
      </el-form-item>
      <el-form-item label="标签组、标签">
        <el-tag  v-for="(it,i) in tagsSnapshot" closable :effect="(it.type==='system')?'':'plain'"  :type="'info'" :key="i" style="margin-right: 5px;margin-top: 5px;cursor: pointer" @close="handleTagGroupClose(i,it)"
                @click="getNameRule(it)">
          {{ it.name }}
        </el-tag>
        <el-tag effect="plain" style="cursor: pointer " @click.native="addTagClick()">
          添加标签
        </el-tag>
      </el-form-item>
      <el-form-item label="关联订单">
        <el-select size="mini" v-model="createTagFrom.offerIds" filterable clearable multiple>
          <el-option v-for="item in offerList" :key="item.id" :value="item.id" :label="item.name"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="tags-template-bottom">
      <el-button type="primary" size="medium" @click="submitTags()">
        保存
      </el-button>
      <el-button size="medium" @click="cancel">
        取消
      </el-button>
    </div>
    <el-drawer
      size="80%" :title="drawerTitle" :visible.sync="isShowEdit" :modal-append-to-body="false" style="width:100%;"
      :close-on-click-modal="false" :before-close="handlerDrawerClose" :append-to-body="true"
    >
      <el-divider></el-divider>
      <div style="margin-left: 20px;margin-top: 20px;">

        <creative-tags-select  ref="tags-select" @on-select="onSelectTags" @on-closed="onCloseTags"
                              :treedata="tempTreeData" :selectTags="selectTags" :tagsSnapshot="tagsSnapshot" @changeTagGroup="changeTagGroup">
        </creative-tags-select>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import CreativeTagsSelect from "@/views/system/components/tagsComponent/CreativeTagsSelect"
import {submitModel} from "@/api/system/creative_tags"
import {deepClone,findObject} from "../../../../util/util";
import func from "../../../../util/func";

export default {
  name: 'createOrEditedCreativeTagsTemplate',
  components: {CreativeTagsSelect},
  comments: {
    CreativeTagsSelect
  },
  computed: {
    tempTreeData() {
      function setParentPath(tree, tagType) {
        tree.map(item => {
            item.tagType = tagType;
          if (item.tagType!=undefined){
            item.id = 'node#' + item.tagType.name + '#' + item.name + '#' + new Date().valueOf();
            if ('tags' in item) {
              let tags = item.tags;
              let tagTypeName = item.tagType.name;
              tags.map(tag => {
                tag.id = tagTypeName + '#' + item.name + '#' + tag.name + '#' + new Date().valueOf();
                tag.nodeId = item.id;
                tag.flag=0;
                tag.check = false
              });
            }
          }
          //有子节点
          if ('groups' in item) {
            if (item.groups && item.groups.length > 0) {
              setParentPath(item.groups,tagType);
            }
          }
        })
      }

      console.log('starTree',this.tagsTree)
      let treeData = deepClone(this.tagsTree)
      // treeData[0].tags = deepClone(treeData[0].groups)
      // treeData[0].groups = null
      treeData.map(item => {

        if (item.type=='system'){
         console.log('system',item)
          let tagType = {};
          tagType.name = item.name;
          tagType.type = item.type;
          item.tagType = tagType;
          if ('groups' in item) {
            item.groups.map(selectItem => {
              let tags = [];
              let nodeId = item.name + '#' + selectItem.name + '#' + new Date().valueOf();
              let tag = {id: nodeId, nodeId: 'node#' + nodeId, tagType: tagType, name: selectItem.name, check: false}
              tags.push(tag);
              selectItem.id = 'node#' + nodeId;
              selectItem.tags = tags;
              selectItem.tagType = tagType;
            });
          }

        }else {
          let tagType = {};
          tagType.name = item.name;
          tagType.type = item.type;
          item.tagType = tagType;
          item.id = 'node#' + item.tagType.name + '#' + item.name + '#' + new Date().valueOf();
          if (item.groups != null && item.groups.length > 0) {
            setParentPath(item.groups, tagType);
          }
          // root tags
          if ('tags' in item){
            let tags = item.tags;
            let tagTypeName = item.tagType.name;
            tags.map(tag => {
              tag.id = tagTypeName + '#' + item.name + '#' + tag.name + '#' + new Date().valueOf();
              tag.nodeId = item.id;
              tag.flag=0;
              tag.check = false
            });
          }
        }

      });
      console.log('deelTree',treeData)
      return treeData;
    },
  },
  watch:{
    nameRules:{
      handler(val,old){
        this.buildName(val);
      },
      deep:true
    },
    tagsSnapshot:{
      handler(val,old){
        // console.log('watch', val.findIndex(item => item.code === "shortId"))
        if (val.findIndex(item => item.code === "shortId") === -1) return
        this.nameRules.forEach((item,index)=>{
          let baseType= findObject(this.tagsSnapshot,item.id,'id')
          if (baseType==null){
            this.nameRules.splice(index,1);
          }
        })
      },
      deep:true
    }

  },
  props: {
    offerList: {
      type: Array,
      default: () => {
      }
    },
    createTagFrom: {
      type: Object
    },
    tagsTree: {
      type: Array,
      default: () => {
      }
    }
  },
  data() {
    return {
      // createTagFrom: {
      //   modelName: "",
      //   offerId: "",
      //   groupDiv: "-",
      //   tagDiv: "-",
      //   radio: 1
      // },
      divList: [
        {label: '-', value: '-'},
        {label: '_', value: '_'},
        {label: '、', value: '、'},
        {label: '/', value: '/'},
        {label: '&', value: '&'},
        {label: '~', value: '~'},
      ],
      rules: {
        modelName: [
          {required: true, message: '请输入模版名称', trigger: 'blur'},
        ],
        offerId: [
          {required: true, message: '请选择订单', trigger: 'blur'},
        ],
        groupDiv: [
          {required: true, message: '请选择分组间隔', trigger: 'blur'},
        ],
        tagDiv: [
          {required: true, message: '请选择同组间隔', trigger: 'blur'},
        ],

      },
      tagsSnapshot: [],
      selectTags: [],
      treeData: [],
      drawerTitle: '添加标签',
      isShowEdit: false,
      offer: null,
      nameRules: [],
      loading: false,
      generateName:''

    }
  },
  mounted() {
    const that = this
    window.onkeypress = function (e) {
      that.$refs.inputRef.focus()
    }
  },
  methods: {
    addTagClick() {
      console.log("addTagClick")
      this.isShowEdit = true;
    },
    changeTagGroup(){
      console.log('changeTagGroup')
      // this.tagsSnapshot=this.buildTempData();
    },
    addNew(){
     // this.radioChange();
      this.addShortId();
    },
    initData() {
      console.log('initData');
      let tagsArray = [];
      if (this.createTagFrom.tagsSnapshot != undefined && this.createTagFrom.tagsSnapshot != '') {
        if (typeof (this.createTagFrom.tagsSnapshot) == 'string') {
          tagsArray = JSON.parse(this.createTagFrom.tagsSnapshot);
        } else {
          tagsArray = this.createTagFrom.tagsSnapshot;
        }
        this.selectTags = [];
        console.log('tagsArray',tagsArray)
        tagsArray.forEach(item => {
          if (item.type == 'system') {
            let tag = {};
            tag.name = item.name;
            tag.code = item.code;
            tag.tagType=item.tagType;
            let tags=[];
            tags.push(tag)
            item.tags=tags;
          } else {
            item.tags.forEach(tag => {
              tag.tagType=item.tagType;
            })
          }
        })
      }
      console.log('deleteTagsArray',tagsArray)
      tagsArray.map(item=>{
          if (item.type == 'system') {
            let node=   this.getNode(this.tempTreeData,item.tagType.name,item.tags)
            if (node!=undefined){
              this.tagsSnapshot.push(node);
            }
          }else {
            console.log('item',item)
           let node=   this.getNode(this.tempTreeData,item.tagType.name,item.tags)
            if (node!=undefined){
              this.tagsSnapshot.push(node);
            }
          }
      });
      this.nameRules=[];
      if (!func.isEmpty(this.createTagFrom.nameRules)) {
        let tempNameRules = JSON.parse(this.createTagFrom.nameRules)
        tempNameRules.map(item => {
          this.tagsSnapshot.map(it => {
            if (item.name == it.name && item.tagType.name == it.tagType.name) {
              this.nameRules.push(it);
              it.tags.map(tag => {
                tag.flag = 1;
              })
            }
          });
        })
      }
      // this.addShortId();
      let node;
      this.tempTreeData[0].groups.map(item=>{
        if (item.code==="shortId"){
          node=item;
          return
        }
      })
      this.nameRules=this.nameRules.filter(item=>{
        if('code' in item && item.code==='shortId'){
          return false;
        }
        return  true;
      });
      this.nameRules.unshift(node)
    },
    getNode(tree,tagType,tagNames){
      console.log('getNode',tagType,tagNames)
      let node;
      let  vm=this;
      function dfNode(tree,tagType,tagNames){
      tree.map(item => {
        if (item.tagType!=undefined) {
          let tagTypeName = item.tagType.name;
          if ('tags' in item) {
            let tags = item.tags;
            let checkTags = [];
            tags.map(tag => {
              if(tagNames!=undefined) {
                tagNames.map(it => {
                  if (tag.name === it.name && tagType === tagTypeName) {
                    console.log('匹配成功')
                    tag.check = true;
                    vm.selectTags.push(tag)
                    checkTags.push(tag)
                  }
                });
              }

            });
            if (checkTags.length > 0) {
              node = deepClone(item);
              node.tags = checkTags;
              // console.log('设置成功')
              return;
            }
          }
        }
        //有子节点
        if ('groups' in item) {
          if (item.groups && item.groups.length > 0) {
            return  dfNode(item.groups,tagType,tagNames);
          }
        }
      });
      }
      dfNode(tree,tagType,tagNames,);
      return node;
    },
    handlerDrawerClose(done) {
      //this.isShowEdit=false
      done();
    },
    cancel() {
      this.$emit('on-close');
    },
    onSelectTags(data) {
      this.isShowEdit = false
      // this.selectTags = data
    },
    addShortId(){
      let node;
      this.tempTreeData[0].groups.map(item=>{
        if (item.code==="shortId"){
          node=item;
          return
        }
      })
      // this.selectTags.forEach((item,index)=>{
      //   if (item.name=='短ID'){
      //     this.selectTags.splice(index,1);
      //   }
      // })
      this.selectTags=this.selectTags.filter(item=>{
          if (item.name=='短ID'){
                return  false;
          }
          return true;
      });
      // this.tagsSnapshot.forEach((item,index)=>{
      //   if('code' in item && item.code==='shortId'){
      //     this.tagsSnapshot.splice(index,1);
      //   }
      // })
      this.tagsSnapshot= this.tagsSnapshot.filter(item=>{
        if('code' in item && item.code==='shortId'){
          return false;
        }
        return  true;
      });
      // this.nameRules.forEach((item,index)=>{
      //   if('code' in item && item.code==='shortId'){
      //     this.nameRules.splice(index,1);
      //   }
      // })
      this.nameRules=this.nameRules.filter(item=>{
          if('code' in item && item.code==='shortId'){
            return false;
          }
          return  true;
      });
      this.selectTags.unshift(node.tags[0])
      this.tagsSnapshot.unshift(node);
      this.nameRules.unshift(this.tagsSnapshot[0])
    },
    handleTagClose(index, item) {
      this.nameRules.splice(index, 1);
    },
    handleTagGroupClose(index,node){
      node.tags.map(item=>{
        item.check=false;
        // this.selectTags.forEach((tag,i)=>{
        //   if (tag.id===item.id){
        //     this.selectTags.splice(i,1);
        //   }
        this.selectTags=this.selectTags.filter(tag=>{
          if (tag.id===item.id){
            return false;
          }
          return  true;
        });
      });
      this.tagsSnapshot.splice(index,1);
    },
    onCloseTags() {
      this.isShowEdit = false
    },
    //标签模版保存
    submitTags() {
      this.$refs['createTagFrom'].validate(valid => {
        if (valid) {
          let parme = {};
          if (this.createTagFrom.groupDiv === this.createTagFrom.tagDiv) {
            this.$message({
              message: '组内分隔和同组分隔不可以使用相同分隔符!',
              type: 'error'
            })
            return
          }
          if (this.tagsSnapshot.length<=0){
            this.$message.warning('未选择标签')
            return;
          }
          //生成命名规则
          if (this.createTagFrom.generateStatus===1){
            if (this.nameRules.length <= 0) {
              this.$message.warning('未选择命名规则')
              return;
            }
          }
          let tagsSnapshotJson=deepClone(this.tagsSnapshot);
          tagsSnapshotJson.map(item=>{
            delete  item.id;
            item.tags.map(tag=>{
              delete tag.id;
              delete  tag.check;
              delete  tag.nodeId;
              if (this.createTagFrom.generateStatus===0){
                tag.flag=0;
              }
            })
          });
          let tempNameRules=deepClone(this.nameRules);
          tempNameRules.map(item=>{
            delete  item.id;
            item.tags.map(tag=>{
              delete tag.id;
              delete  tag.check;
              delete  tag.nodeId;
              if (this.createTagFrom.generateStatus===0){
                tag.flag=0;
              }else {
                tag.flag=1;
              }
            })
          });

          if (this.createTagFrom.id != undefined) {
            parme.id = this.createTagFrom.id;
          }
          parme.modelName = this.createTagFrom.modelName;
          parme.groupDiv = this.createTagFrom.groupDiv;
          parme.tagDiv = this.createTagFrom.tagDiv;
          parme.offerIds = this.createTagFrom.offerIds.join(',');
          parme.generateStatus = this.createTagFrom.generateStatus;
          parme.generateName = this.buildName(tempNameRules);
          parme.nameRules = JSON.stringify(tempNameRules);
          parme.tagsSnapshot = JSON.stringify(tagsSnapshotJson);
          this.loading = true;
          submitModel(parme).then(res => {
            this.loading = false;
            if (parme.id!=undefined){
              this.$message.success('修改模版成功')
            }else {
              this.$message.success('添加模版成功')
            }
            this.$refs['createTagFrom'].resetFields();
            this.$emit('on-close', 'update');
          }).catch(e => {
            this.loading = false;
          });
        }
      });

    },
    getNameRule(tag) {
      if (tag.name=='短ID'){
        return
      }
      if (!this.nameRules.includes(tag)) {
        tag.tags.map(item=>{
          item.flag=1;
        })
        this.nameRules.push(tag)
      }
    },
    buildName(nameRules) {
      let name='';
      if (nameRules.length>0){
        nameRules.map(item=>{
          if (item.type=='system'){
            if (name===''){
              name+='{'+item.code+'}';
            }else {
              name+=this.createTagFrom.groupDiv+'{'+item.code+'}';
            }

          }else {
            let tags=item.tags;
            tags.forEach((it,index)=>{
              if (index==0){
                name+= this.createTagFrom.groupDiv+it.name
              }else {
                name+= this.createTagFrom.tagDiv+it.name
              }
            })
          }
        });
      }
      this.generateName=name;
      return name;
    }
  },
}
</script>

<style lang="scss" scoped>
.root {
  height: 90vh;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .el-input {
    width: 220px;
  }
  .demo-ruleForm {
    overflow: auto;
  }
  .tags-template-bottom {
    width: 100%;
    text-align: center;
    flex: 0;
  }
}
</style>
